package com.zyh.websocket.service;

import com.zyh.common.core.domain.entity.SysUser;
import com.zyh.counselor.service.ICounselorService;
import com.zyh.system.service.ISysUserService;
import com.zyh.websocket.constant.MessageConstant;
import com.zyh.websocket.entity.Message;
import com.zyh.websocket.service.chat.MessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Slf4j
@Service
@RequiredArgsConstructor
public class MessageReceiverService {
    private final MessageService messageService;
    private final MessageSenderService senderService;
    private final MessageBaseService baseService;
    private final ISysUserService userService;
    private final ICounselorService counselorService;

    @Transactional
    public void handleMessage(Message rawMessage, Long senderId) {
        try {
            // 校验发送者
            SysUser sender = userService.getById(senderId);
            if (Objects.isNull(sender) || "2".equals(sender.getDelFlag())) {
                throw new IllegalArgumentException("无效的发送者ID: " + senderId);
            }

            // 构建消息
            Message message = baseService.buildMessage(rawMessage, senderId);
            message.setCreateBy(sender.getUserName());

            // 消息路由处理
            switch (message.getType()) {
                // 系统消息、聊天消息、审批流程、预约流程
                case MessageConstant.SYSTEM_MSG -> handleSystemMessage(message);
                case MessageConstant.CHAT_MSG -> handleChatMessage(message);
                case MessageConstant.APPROVAL_MSG -> handleApprovalMessage(message);
                case MessageConstant.APPOINTMENT_MSG -> handleAppointmentMessage(message);
                default -> throw new IllegalArgumentException("非法的消息类型: " + message.getType());
            }

            // 持久化存储
            messageService.save(message);
            logMessageFlow(senderId, message);

        } catch (Exception e) {
            log.error("消息处理失败: {}", e.getMessage());
            throw e;
        }
    }

    // 系统消息处理
    private void handleSystemMessage(Message message) {
        if (MessageConstant.SubType.SYSTEM_BROADCAST.equals(message.getSubType())) {
            senderService.broadcastSystemMessage(message);
        } else {
            throw new IllegalArgumentException("未知系统消息子类型: " + message.getSubType());
        }
    }

    // 聊天消息处理
    private void handleChatMessage(Message message) {
        validateParticipants(message);
        senderService.sendPrivateMessage(message);
    }

    // 审批流程处理
    private void handleApprovalMessage(Message message) {
        //case MessageConstant.SubType.APPROVAL_REQUEST -> senderService.sendApprovalRequest(message);
        if (message.getSubType().equals(MessageConstant.SubType.APPROVAL_RESULT)) {
            senderService.sendApprovalResult(message);
        } else {
            throw new IllegalArgumentException("非法审批类型: " + message.getSubType());
        }
    }

    // 预约流程处理
    private void handleAppointmentMessage(Message message) {
        if (message.getSubType().equals(MessageConstant.SubType.APPOINTMENT_REQUEST)) {
            validateCounselor(message.getReceiverId());
            senderService.sendAppointmentRequest(message);
            //case MessageConstant.SubType.APPOINTMENT_RESULT -> senderService.sendAppointmentResult(message);
        } else {
            throw new IllegalArgumentException("非法预约类型: " + message.getSubType());
        }
    }

    private void validateParticipants(Message message) {
        if (message.getSenderId().equals(message.getReceiverId())) {
            throw new IllegalArgumentException("不能给自己发消息");
        }
        if (Objects.isNull(userService.getById(message.getReceiverId()))) {
            throw new IllegalArgumentException("接收用户不存在");
        }
    }

    private void validateCounselor(Long userId) {
        if (!counselorService.isCounselor(userId)) {
            throw new IllegalArgumentException("接收方必须是咨询师");
        }
    }

    private void logMessageFlow(Long senderId, Message message) {
        log.info("消息流转 - 发送者:{} → 接收者:{} | 类型:{}/{} | 内容:{}",
                senderId, message.getReceiverId(),
                message.getType(), message.getSubType(),
                message.getContent());
    }
}
